package com.will.yuaiagent.agent;

import cn.hutool.core.util.ObjectUtil;
import com.will.yuaiagent.exception.BusinessException;
import com.will.yuaiagent.exception.ErrorCode;
import com.will.yuaiagent.exception.ThrowUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * @author will
 * @since 2025/7/24 19:01
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class ReActAgent extends BaseAgent {
    /**
     * 处理当前状态并执行下一步行动
     * @return 是否需要执行行动，true表示需要执行行动，false表示不需要执行行动
     */
    public abstract boolean think();

    /**
     * 执行行动
     * @return 动作结果
     */
    public abstract String act();

    @Override
    public String step() {
        /* Execute a single step: think and act. */
        try {
            boolean shouldAct = think();
            if (!shouldAct) {
                String text = getChatClient().prompt(getSystemPrompt())
                        .user(getNextStepPrompt())
                        .call()
                        .chatResponse()
                        .getResult()
                        .getOutput()
                        .getText();
                return "Thinking: complete - no action needed \n" + "result: " + text;
            }
            return act();
        } catch (Exception e) {
            ThrowUtils.throwIf(ObjectUtil.isEmpty(e), ErrorCode.SYSTEM_ERROR, "Error executing agent: " + e.getMessage());
            return "Error executing agent: " + e.getMessage();
        }
    }
}
